<template>
    <div>
        <!--        面包屑导航栏-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <!--            添加角色按钮-->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <!--            角色列表区-->
            <el-table :data="rolesList" stripe border>
                <!--                展开列-->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="(item1,index1) in scope.row.children" :key="item1.id"
                                :class="['bdBottom', index1 === 0 ? 'bdTop' : '','v-center']">
                            <!--                            一级权限-->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightsById(scope.row,item1.id)">{{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--                            二级权限和三级权限-->
                            <el-col :span="19">
                                <el-row v-for="(item2,index2) in item1.children" :key="item2.id"
                                        :class="[index2 === 0 ? '' : 'bdTop','v-center']">
                                    <!--                                    二级权限-->
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightsById(scope.row,item2.id)">
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!--                                    三级权限-->
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3,index3) in item2.children" :key="item3.id"
                                                closable @close="removeRightsById(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#" align="center"></el-table-column>
                <el-table-column label="角色名称" prop="roleName" align="center"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit"
                                   @click="showEditRoleDialog(scope.row.id)">编辑
                        </el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">
                            删除
                        </el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting"
                                   @click="showSetRightsDialog(scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!--        添加角色对话框-->
        <el-dialog
                title="添加角色"
                :visible.sync="addDialogVisible"
                @close="addDialogClosed"
                width="35%">
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRole">确 定</el-button>
  </span>
        </el-dialog>
        <!--        编辑角色对话框-->
        <el-dialog
                title="编辑角色"
                :visible.sync="editDialogVisible"
                width="35%">
            <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRole">确 定</el-button>
  </span>
        </el-dialog>
        <!--        分配权限对话框-->
        <el-dialog
                title="分配权限"
                :visible.sync="setRightsDialogVisible"
                @close="setRightsDialogClosed"
                width="45%">
            <!--            树型控件-->
            <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
                     :default-checked-keys="defKeys"
                     ref="treeRef"
            ></el-tree>
            <span slot="footer" class="dialog-footer">
    <el-button @click="setRightsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>

<script>

    export default {
        name: "Roles",
        data() {
            return {
                rolesList: [],
                // 添加角色
                addDialogVisible: false,
                addForm: {
                    roleName: '',
                    roleDesc: '',
                },
                addFormRules: {
                    roleName: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'},
                        {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
                    ],
                    roleDesc: [
                        {required: true, message: '请输入角色描述', trigger: 'blur'},
                        {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
                    ],
                },
                // 编辑角色
                editDialogVisible: false,
                editForm: {},
                editFormRules: {
                    roleName: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'},
                        {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}
                    ],
                    roleDesc: [
                        {required: true, message: '请输入角色描述', trigger: 'blur'},
                        {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
                    ],
                },
                // 分配权限
                setRightsDialogVisible: false,
                rightsList: [],
                treeProps: {
                    label: 'authName',
                    children: 'children'
                },
                // 默认勾选的结点
                defKeys: [],
                roleId: '',
            }
        },
        created() {
            this.getRolesList()
        },
        methods: {
            async getRolesList() {
                const res = (await this.$http.get('roles')).data
                if (res.meta.status !== 200) {
                    return this.$message.error({
                        message: '获取角色列表失败!',
                        center: true
                    })
                } else {
                    this.rolesList = res.data
                }
            },
            async removeRightsById(role, rightId) {
                const res = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (res === 'cancel') {
                    return this.$message.info({
                        message: '已取消删除!',
                        center: true
                    })
                } else {
                    const res = (await this.$http.delete(`roles/${role.id}/rights/${rightId}`)).data
                    if (res.meta.status !== 200) {
                        return this.$message.error({
                            message: "删除权限失败!",
                            center: true
                        })
                    } else {
                        this.$message.success({
                            message: '删除权限成功!',
                            center: true
                        })
                        console.log(res);
                        role.children = res.data
                    }
                }
            },
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()
            },
            addRole() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) {
                        return
                    } else {
                        const res = (await this.$http.post('roles', this.addForm)).data
                        if (res.meta.status !== 201) {
                            this.$message.error({
                                message: '添加角色失败!',
                                center: true
                            })
                        } else {
                            this.$message.success({
                                message: '添加角色成功!',
                                center: true
                            })
                            this.addDialogVisible = false
                            await this.getRolesList()
                        }
                    }
                })
            },
            async showEditRoleDialog(id) {
                this.editDialogVisible = true
                const res = (await this.$http.get('roles/' + id)).data
                if (res.meta.status != 200) {
                    return this.$message.error({
                        message: '查询角色失败!',
                        center: true
                    })
                } else {
                    this.editForm = res.data
                }
            },
            async editRole() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) {
                        return
                    } else {
                        const res = (await this.$http.put('roles/' + this.editForm.roleId, {
                            roleName: this.editForm.roleName,
                            roleDesc: this.editForm.roleDesc
                        })).data
                        if (res.meta.status !== 200) {
                            console.log(res);
                            return this.$message.error({
                                message: '修改失败!',
                                center: true
                            })
                        } else {
                            this.$message.success({
                                message: '修改成功!',
                                center: true
                            })
                            await this.getRolesList()
                            this.editDialogVisible = false
                        }
                    }
                })
            },
            async deleteRole(id) {
                const res = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (res === 'cancel') {
                    this.$message.info({
                        message: '已取消删除!',
                        center: true
                    })
                } else {
                    const res = (await this.$http.delete('roles/' + id)).data
                    if (res.meta.status !== 200) {
                        this.$message.error({
                            message: '删除失败!',
                            center: true
                        })
                    } else {
                        this.$message.success({
                            message: '删除成功！',
                            center: true
                        })
                        await this.getRolesList()
                    }
                }
            },
            async showSetRightsDialog(role) {
                this.roleId = role.id
                const res = (await this.$http.get('rights/tree')).data
                if (res.meta.status !== 200) {
                    this.$message.error({
                        message: '获取权限失败!',
                        center: true
                    })
                } else {
                    this.rightsList = res.data
                    this.getLeafKeys(role, this.defKeys)
                    this.setRightsDialogVisible = true
                }
            },
            // 通过递归获取所有三级权限下的ID
            getLeafKeys(node, arr) {
                if (!node.children) {
                    return arr.push(node.id)
                }
                node.children.forEach(item => {
                    this.getLeafKeys(item, arr)
                })
            },
            setRightsDialogClosed() {
                this.defKeys = []
            },
            // 分配权限
            async allotRights() {
                this.setRightsDialogVisible = false
                // 获取选中和半选中的结点的ID
                const keys = [
                    ...this.$refs.treeRef.getCheckedKeys(),
                    ...this.$refs.treeRef.getHalfCheckedKeys()
                ]
                const idStr = keys.join(',')
                const res = (await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr})).data
                if (res.meta.status !== 200) {
                    this.$message.error({
                        message: '分配权限失败!',
                        center: true
                    })
                } else {
                    this.$message.success({
                        message: '分配权限成功!',
                        center: true
                    })
                    await this.getRolesList()
                }
            }
        }
    }
</script>

<style scoped>
    .el-tag {
        margin: 7px;
    }

    .bdBottom {
        border-bottom: 1px solid #eee;
    }

    .bdTop {
        border-top: 1px solid #eee;
    }

    .v-center {
        display: flex;
        align-items: center;
    }
</style>